<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-input style="width: 200px;" v-model="find_data.find" placeholder="客户姓名电话关键字" clearable
                        prefix-icon="Search" />
                    <el-input type="number" style="width: 120px; margin-left:20px" v-model="find_data.checkInCustomers"
                        placeholder="入住人数" clearable prefix-icon="User" />

                    <el-input type="number" style="width: 170px; margin-left:20px"
                        v-model="find_data.totalFreeTransferCount" placeholder="剩余免费接送次数" clearable
                        prefix-icon="Promotion" />

                    <el-select style="margin-left: 20px;width:130px" v-model="find_data.timeType" placeholder="查询时间类型 "
                        clearable>
                        <el-option v-for="item in timeType" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>

                    <el-date-picker value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
                        style="width: 180px;margin-left: 20px;" v-model="find_data.stime" type="datetime"
                        placeholder="查询开始时间" />

                    <el-date-picker value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
                        style="width: 180px;margin-left: 20px;" v-model="find_data.etime" type="datetime"
                        placeholder="查询结束时间" />

                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;display: flex;">
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">添加</el-button>
                    <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>

                    <!-- <div style="margin-left:15px"> <el-upload :data="{ checkInFile: '单位客户入住信息' }"
                            :headers="{ 'token': GET_TOKEN(), 'Content-Type': 'multipart/form-data' }" class="upload-excel"
                            :action="importCusCheckInData" :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <el-button type="warning" icon="Share">导入</el-button>
                        </el-upload></div> -->

                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field"
                            :label="item.label"></el-table-column>
                    </template>


                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true" layout="prev, pager, next, jumper,->,sizes,total,"
                    :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:100px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="40%" :close-on-click-modal='false'>
            <el-form :model="add_data" label-width="130px" label-suffix="：">
                <el-form-item label="入住人数">
                    <el-input style="width: 220px;" type="number" v-model="add_data.checkInCustomers"
                        placeholder="请输入入住人数" />
                </el-form-item>
                <div style="display: flex;">
                    <el-form-item label="入住放间号" :required="false">
                        <el-input style="width:220px" type="number" v-model="checkInRoomNo_data" placeholder="请输入入住放间号" />
                        <el-button style="margin-left:20px" @click="checkInRoomNo_btn" type="primary"
                            icon="Plus">添加</el-button>
                    </el-form-item>
                </div>
                <div v-if="checkInRoomNo_data_list.length > 0">
                    <el-tag style="margin-left:10px;margin-bottom:10px" v-for="  item   in   checkInRoomNo_data_list  "
                        :key="item" class="mx-1" closable type="danger" @close="close_btn(item)">
                        房间号:{{ item }}
                    </el-tag>
                </div>
                <el-form-item label="入住时间" :required="false">
                    <el-date-picker value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
                        v-model="add_data.checkInTime" type="datetime" placeholder="请选择入住时间" />
                </el-form-item>
                <el-form-item label="离店时间" :required="false">
                    <el-date-picker value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
                        v-model="add_data.checkOutTime" type="datetime" placeholder="请选择离店时间" />
                </el-form-item>
                <el-form-item label="免费接送站点">
                    <el-select style="width: 220px;" v-model="add_data.freeTransferStationId" placeholder="请选择免费接送站点 "
                        clearable>
                        <el-option v-for="  item   in   findStationCombo_data_list  " :key="item.id"
                            :label="item.station_name" :value="item.id" />
                    </el-select>

                </el-form-item>
                <el-form-item label="总免费接送人数">
                    <el-input style="width: 220px;" type="number" v-model="add_data.totalFreeTransferCount"
                        placeholder="请输入总免费接送人数" />
                </el-form-item>
                <el-form-item label="乘车联系人姓名">
                    <el-input style="width: 220px;" v-model="add_data.linkName" placeholder="请输入乘车联系人姓名" />
                </el-form-item>
                <el-form-item label="乘车联系人电话">
                    <el-input style="width: 220px;" type="number" v-model="add_data.linkPhone" placeholder="请输入乘车联系人电话" />
                </el-form-item>

                <el-form-item label="备注">
                    <el-input show-word-limit maxlength="30" type="textarea" v-model="add_data.note" />
                </el-form-item>

            </el-form>


            <el-button @click="ok_btn" style="margin-left:30vw" type="primary">确认提交</el-button>
        </el-dialog>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { GET_TOKEN } from '@/utils/token.js'
import { ref, reactive, onMounted, computed } from 'vue'
import {
    getCustomCheckInfoPages, adupCustomCheckInfo, findStationCombo, getStationType, delCustomCheckInfo, adupPrivateSet, getPrivateSetList

} from '@/api/check_in_record_list.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { importCusCheckInData } from '@/utils/common.js'
import CircularJSON from 'circular-json'
onMounted(async () => {
    let check_in_record_list = JSON.parse(localStorage.getItem('check_in_record_list'))
    if (check_in_record_list) {
        find_data.checkInCustomers = check_in_record_list.checkInCustomers
        find_data.stime = check_in_record_list.stime
        find_data.etime = check_in_record_list.etime
        find_data.timeType = check_in_record_list.timeType
        find_data.find = check_in_record_list.find
        find_data.totalFreeTransferCount = check_in_record_list.totalFreeTransferCount

    }

    getPrivateSetList({
        find: '入住记录',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            console.log('no')
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })





    await list_api()
    getStationType({}).then(res => {
        console.log(res)
    })
})

//#region 表格数据处理
const table_data_list = reactive([
    { label: '客户姓名', field: 'linkName', width: 85, off: true },
    { label: '联系电话', field: 'linkPhone', width: 120, off: true },
    { label: '人数', field: 'checkInCustomers', width: 80, off: true },
    { label: '入住时间', field: 'checkInTime', width: 170, off: true },
    { label: '离店时间', field: 'checkOutTime', width: 170, off: true },
    { label: '入住房间号', field: 'checkInRoomNo', width: 170, off: true },
    { label: '免费接送机场', field: 'stationName', width: 150, off: true },
    { label: '本次入住总免费接送次数', field: 'totalFreeTransferCount', width: 195, off: true },
    { label: '备注', field: 'note', width: 270, off: true },
    { label: '添加时间', field: 'addTime', width: 180, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '入住记录',
        tbNum: "check_in_record_list",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion


//#region 查询时间类型
const timeType = reactive([
    {
        value: '0',
        label: '入住日期',
    },
    {
        value: '1',
        label: '离店日期',
    }, {
        value: '2',
        label: '添加日期',
    },
])
//#endregion
//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    checkInCustomers: '',
    stime: '',
    etime: '',
    timeType: "0",
    totalFreeTransferCount: "",
    find: '',
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    getCustomCheckInfoPages(find_data).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total
    })
}
//#endregion

//#region 添加
const add_off = ref(false)
const title = ref('添加单位客户入住信息')
const checkInRoomNo_data = ref('')
const checkInRoomNo_data_list = ref([])
const checkInRoomNo_btn = () => {
    if (!checkInRoomNo_data.value) {
        return ElMessage({
            message: '房间号不能为空',
            type: 'warning',
        })
    }
    for (let i = 0; i < checkInRoomNo_data_list.value.length; i++) {
        if (checkInRoomNo_data.value == checkInRoomNo_data_list.value[i]) {
            return ElMessage({
                message: '房间号已存在',
                type: 'warning',
            })
        }
    }
    checkInRoomNo_data_list.value.push(checkInRoomNo_data.value)
    checkInRoomNo_data.value = ''
}
const close_btn = (e) => {
    let index = checkInRoomNo_data_list.value.indexOf(e);
    if (index !== -1) {
        checkInRoomNo_data_list.value.splice(index, 1);
    }
}
const add_data = reactive({
    checkInCustomers: '',
    checkInRoomNo: '',
    checkInTime: "",
    checkOutTime: "",
    freeTransferStationId: "",
    id: "",
    linkName: "",
    linkPhone: "",
    note: "",
    totalFreeTransferCount: "",
})
const findStationCombo_data_list = ref([])
const add_btn = () => {
    title.value = '添加单位客户入住信息'
    checkInRoomNo_data.value = ''
    checkInRoomNo_data_list.value = []
    add_data.checkInCustomers = ''
    add_data.checkInRoomNo = ''
    add_data.checkInTime = ''
    add_data.checkOutTime = ''
    add_data.freeTransferStationId = ''
    add_data.id = ''
    add_data.linkName = ''
    add_data.linkPhone = ''
    add_data.note = ''
    add_data.totalFreeTransferCount = ''
    findStationCombo({
        find: '',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        stationTypes: ['AIRPORT'],

    }).then(res => {
        findStationCombo_data_list.value = res.data.list
    })


    add_off.value = true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    findStationCombo({
        find: '',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        stationTypes: ['AIRPORT'],

    }).then(res => {
        findStationCombo_data_list.value = res.data.list
    })

    title.value = '修改单位客户入住信息'
    checkInRoomNo_data.value = ''
    checkInRoomNo_data_list.value = table_list.value[0].checkInRoomNo.split(",")
    add_data.checkInCustomers = table_list.value[0].checkInCustomers
    add_data.checkInRoomNo = ''
    add_data.checkInTime = table_list.value[0].checkInTime
    add_data.checkOutTime = table_list.value[0].checkOutTime
    add_data.freeTransferStationId = table_list.value[0].freeTransferStationId
    add_data.id = table_list.value[0].id
    add_data.linkName = table_list.value[0].linkName
    add_data.linkPhone = table_list.value[0].linkPhone
    add_data.note = table_list.value[0].note
    add_data.totalFreeTransferCount = table_list.value[0].totalFreeTransferCount


    add_off.value = true
}
//#endregion

// 提交
const ok_btn = () => {
    if (checkInRoomNo_data.value) {
        let data_off = 0
        for (let i = 0; i < checkInRoomNo_data_list.value.length; i++) {
            if (checkInRoomNo_data.value == checkInRoomNo_data_list.value[i]) {
                data_off = 1
            }
        }
        if (data_off == 0) {
            checkInRoomNo_data_list.value.push(checkInRoomNo_data.value)
        }
    }
    if (checkInRoomNo_data_list.value.length > 0) {
        add_data.checkInRoomNo = checkInRoomNo_data_list.value.join(',')
    }
    if (!add_data.checkInCustomers) {
        return ElMessage({
            message: '请输入入住人数',
            type: 'warning',
        })
    } else if (!add_data.checkInTime) {
        return ElMessage({
            message: '请选择入住时间',
            type: 'warning',
        })
    } else if (!add_data.checkOutTime) {
        return ElMessage({
            message: '请选择离店时间',
            type: 'warning',
        })
    } else if (!add_data.freeTransferStationId) {
        return ElMessage({
            message: '请选择免费接送站点',
            type: 'warning',
        })
    } else if (!add_data.linkName) {
        return ElMessage({
            message: '请选择输入乘车联系人姓名',
            type: 'warning',
        })
    } else if (!add_data.linkPhone) {
        return ElMessage({
            message: '请选择输入乘车联系人电话',
            type: 'warning',
        })
    } else if (!add_data.totalFreeTransferCount) {
        return ElMessage({
            message: '请选择输入总免费接送人数',
            type: 'warning',
        })
    } else if (!add_data.checkInRoomNo) {
        return ElMessage({
            message: '请选择输入房间号',
            type: 'warning',
        })
    }







    if (title.value == '添加单位客户入住信息') {



        adupCustomCheckInfo(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    } else {

        adupCustomCheckInfo(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    }
}


//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        '是否确认删除客户?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delCustomCheckInfo({
                ids: [table_list.value[0].id]
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 搜索
const search_btn = () => {
    localStorage.setItem('check_in_record_list', CircularJSON.stringify(find_data))
    list_api()
}
//#endregion

//#region 导入
const handleAvatarSuccess = (response, uploadFile) => {
    console.log(response)
    // return ElMessage({
    //                     message: res.msg,
    //                     type: 'success',
    //                 })
}

const beforeAvatarUpload = (rawFile) => {
    console.log(rawFile)
    let type = rawFile.name.split('.')[rawFile.name.split('.').length - 1]
    if (type == 'xlsx' || type == 'xls' || type == 'csv') {
        return true
    } else {
        return ElMessage.error('请上传Excel文件!')
    }

}
//#endregion

</script>

<style scoped lang='scss'>
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
